package controller

import (
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"week1zk-project/api/client"
	"week1zk-project/api/pkg"
	"week1zk-project/api/types"
	pb "week1zk-project/user-rpc/api/user"
)

//用户注册

func UserRegister(c *gin.Context) {
	var userRegister types.UserRegisterReq
	if err := c.ShouldBindJSON(&userRegister); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "服务器内部错误",
			"err":  err.Error(),
		})
		return
	}
	// 4. 调用接口
	res, err := client.UserClient().UserRegister(context.Background(), &pb.UserRegisterRequest{
		Username:   userRegister.Username,
		Password:   userRegister.Password,
		ConfirmPwd: userRegister.ConfirmPwd,
		Email:      userRegister.Email,
		Mobile:     userRegister.Mobile,
	})
	//检验是否为空
	if userRegister.Username == "" || userRegister.Password == "" || userRegister.ConfirmPwd == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "请确认您是否填写用户名或密码",
		})
		return
	}
	//邮箱不为空
	if userRegister.Email == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "请输入您的邮箱",
		})
		return
	}
	//校验手机号码格式
	if len(userRegister.Mobile) != 11 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "请输入正确的手机号码",
		})
		return
	}
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": res.Code,
			"msg":  res.Msg,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": res.Code,
		"msg":  res.Msg,
		"data": res.UserId,
	})
}

//用户登录

func UserLoginReq(c *gin.Context) {
	var userLogin types.UserLoginReq
	if err := c.ShouldBindJSON(&userLogin); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "服务器内部错误",
			"err":  err.Error(),
		})
		return
	}
	// 4. 调用接口
	res, err := client.UserClient().UserLogin(context.Background(), &pb.UserLoginRequest{
		Username: userLogin.Username,
		Password: pkg.Md5(userLogin.Password),
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": res.Code,
			"msg":  res.Msg,
		})
		return
	}
	if res.UserId == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "此用户不存在",
		})
		return
	}
	//检验是否为空
	if userLogin.Username == "" || userLogin.Password == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "请确认您是否填写用户名或密码",
		})
		return
	}

	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": "token生成失败",
			"msg":  err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": res.Code,
		"msg":  res.Msg,
		"data": res.UserId,
	})
}
